package mil.af.amc.adpetracker.web.actions.EquipmentItem;

import mil.af.amc.adpetracker.model.EquipmentItem;
import mil.af.amc.adpetracker.service.EquipmentItemService;
import mil.af.amc.adpetracker.web.actions.AbstractAction;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * AJAX-specific action to get a list of EquipmentItem object by their associated ItemModel
 *
 * @author TSgt Jason Ferguson
 */

public class GetEquipmentItemsByItemModelAction extends AbstractAction {

    private EquipmentItemService equipmentItemService;

    public void setEquipmentItemService(EquipmentItemService equipmentItemService) {
        this.equipmentItemService = equipmentItemService;
    }

    @Override
    public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {

        Integer id = Integer.parseInt(httpServletRequest.getParameter("id"));

        List<EquipmentItem> equipmentItemList = equipmentItemService.getAllByItemModel(id);
        Collections.sort(equipmentItemList);

        // Build the JSON object manually to avoid json-lib's "cycle in the hierarchy" crap
        JSONArray jsonArray = new JSONArray();
        for (EquipmentItem item : equipmentItemList) {

            Map<String, Object> itemMap = new HashMap<String, Object>();
            itemMap.put("id", item.getId());
            itemMap.put("name", item.getSerial());
            JSONObject jsonObject = JSONObject.fromObject(itemMap);
            jsonArray.add(jsonObject);
        }

        httpServletResponse.setHeader("Content-Type","application/json");
        httpServletResponse.getWriter().println(jsonArray);

        return null;

    }
}
